package com.hngm.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.startup.SetContextPropertiesRule;

/**
 * Servlet Filter implementation class LoginFilter
 */
public class LoginFilter implements Filter {

    /**
     * 构造方法 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * 销毁方法
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * 实现过滤逻辑的方法
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		PrintWriter out = resp.getWriter();
		
		//获取用户请求的地址
		String request_url = req.getRequestURI();
		String ctxPath = req.getContextPath();
		
		//获取session
		HttpSession session = req.getSession();
		
		if(request_url.contains("login.jsp") || request_url.contains("LoginServlet")){
			//放行
			chain.doFilter(request, response);
		}else{
			//实现登陆验证的操作
			if(session.getAttribute("userInfo") != null){
				//如果用户信息不为空，则放行
				//放行
				chain.doFilter(request, response);
			}else{
				//没有登陆跳转到登陆页面
				out.print("您还没有登陆，请先去登陆！3秒后回到登陆页面");
				resp.setHeader("refresh", "3;url=/corpor12/login.jsp");
			}
		}
		out.flush();
		out.close();	
	}

	/**
	 * 初始化方法
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
